// JavaScript Document

/**********************************
 * PURPOSE: a simple file utility class for handling several file related
 * client side functionalities, including viewing source code, listing files
 * in the directory viewer, deleting content and setting up files for upload
 *
 */

var file_utils = {

    processorPage: '../cms/utils/file_utils.php',
    filePath: null,
	
	codeEditor: null,
	
    /**
	 * Generates the required HTML structure to make this editor feature work
	 */
    init: function() {
        var editContent = '<div id="editor_overlay"></div>'
        + '<div id="editor_container">'
        + '  <div id="editor_wrapper">'
        + '    <div id="editor_bar">'
        + '      <a href="javascript:file_utils.saveEditorContent();">Save & Continue</a> |'
        + '      <a href="javascript: file_utils.saveEditorContent(file_utils.hideOverlayedEditor);">Save & Close</a> |'
        + '      <a href="javascript:file_utils.hideOverlayedEditor();">Close</a>'
        + '    </div>'
        + '    <div id="editor_box"></div>'
        + '    <div id="fu-ajax-result"></div>'
        + '  </div>'
        + '</div>';
			
        var editArea = document.createElement("div");
        editArea.innerHTML = editContent;
		
        var bodyEl = document.getElementsByTagName("body")[0];
        bodyEl.appendChild(editArea);
    },
	
    /**
     * Shows the file editor component in an overlayed container
     */
    showOverlayedEditor: function(filePath, mimeType) {

		pageManager.fadeIn("editor_overlay", function() {
			pageManager.show("editor_container");
		}, 50);
		
        if( filePath != null ) {
			
			var query = "action=show_file&FilePath=" + filePath + "&mimeType=" + mimeType;
            pageManager.post( file_utils.processorPage, query, function(data) {
				$p('#editor_box').html(data);

				var pfs = ["tokenizejavascript.js", "parsejavascript.js"];
			
				switch(mimeType) {
					case 'text/javascript':
						pfs = ["tokenizejavascript.js", "parsejavascript.js"];
						break;
					case 'text/css':
						pfs = "parsecss.js";
						break;
					case 'text/xml':
						pfs = "parsexml.js";
						break;
					case 'text/php':
					case 'text/html':
					default:
						pfs = ["parsexml.js", "parsecss.js", "tokenizejavascript.js", "parsejavascript.js", "parsehtmlmixed.js",
									 "../contrib/php/js/tokenizephp.js", "../contrib/php/js/parsephp.js", "../contrib/php/js/parsephphtmlmixed.js"];
						break;
				}
				
				file_utils.codeEditor = CodeMirror.fromTextArea('EditorContent', {
					
					parserfile: pfs,
					stylesheet: ["../cms/scripts/code_mirror/css/xmlcolors.css", 
								 "../cms/scripts/code_mirror/css/jscolors.css", 
								 "../cms/scripts/code_mirror/css/csscolors.css", 
								 "../cms/scripts/code_mirror/contrib/php/css/phpcolors.css"],
					path: "../cms/scripts/code_mirror/js/",
					continuousScanning: 500,
					textWrapping: false,
					autoMatchParens: true
				});
			} );

            // cache the filePath of the currently editted file
            file_utils.filePath = filePath;
        }
    },

    /**
     * Saves the contents of the file editor back to the file on the server.
     * A callback may be supplied which would be called after the file is saved.
     */
    saveEditorContent: function(callback) {
        if( !confirm("Save Changes Made To The Current Document?") ) {
            return;
        }
		
        var data = file_utils.getEditorContent();
        var query = "action=save_file&EditorContent=" + encodeURIComponent(data) + "&FilePath=" + file_utils.filePath;
        pageManager.post(file_utils.processorPage, query, function(data) {
			$p('#fu-ajax-result').html(data);
			
			if( callback && $p.isFunction(callback) ) {
				callback();	
			}
		});
    },

    /**
     * Hides the editor and the overlay container
     */
    hideOverlayedEditor: function() {
        document.getElementById("editor_overlay").style.display = "none";
        document.getElementById("editor_container").style.display = "none";
    },

    /**
     * Returns the contents of the file editor control
     **/
    getEditorContent: function() {
        //return document.getElementById("editorApplet").getEditorContent();
		if( file_utils.codeEditor == null ) {
			return "";	
		}
		
		return file_utils.codeEditor.getCode();
    },

    /**
     * Supplies the contents of the file to be editted to the editor control
     */
    setEditorContent: function(data) {
        /*var hf = document.getElementById("EditorContent");
		
        if( data != null && hf != null ) {
            hf.value = data;
        }
		
        document.getElementById("editorApplet").setEditorContent( hf.value );
        document.getElementById("editorApplet").getEditorComponent().setCaretPosition( 0 );*/
		
		if( file_utils.codeEditor != null ) {
			file_utils.codeEditor.setCode(data);	
		}
    },

    /**
     * Stores the supplied content to the editor textarea control
     */
    storeEditorContent: function(content) {
        var hf = document.getElementById("EditorContent");
		
        if( hf != null && content != null ) {
            hf.value = content;
        }
    },
	
    /**
     * Attaches the necessary event handlers to the generated Folder Tree
     * to enable the folders be expanded or collapsed as necessary
     */
    attachFolderHandlers: function() {
        var dirTree = document.getElementById("dir_tree");
		
		if( dirTree == null ) {
			return;
		}
		
        var liNodes = dirTree.getElementsByTagName("li");
		
        for(var i = 0; i < liNodes.length; i++) {
            var node = liNodes.item(i);
			
            if( node.className == "dir_name" ) {
                node.onclick = function(e) {
					if(!e) var e = window.event;
					
                    var uls = this.getElementsByTagName("ul");
					
                    for(var x = 0; x < uls.length; x++) {
                        var ul = uls.item(x);
                        if( ul.parentNode == this ) { // only expand direct childNodes
                            if( ul.style.display == "block" ) {
                                ul.style.display = "none";
                            } else {
                                ul.style.display = "block";
                            }
                        }
                    }
					
                    file_utils.stopEvent(e);
                }
            }
			
            if( node.className == "file_name" ) {
                // prevent unnecesarry expansion of tree nodes
                node.onclick = function(e) {
					file_utils.stopEvent(e);
                }
            }
        }
    },
	
	stopEvent: function (e) {
		if(!e) var e = window.event;
		
		//e.cancelBubble is supported by IE - this will kill the bubbling process.
		e.cancelBubble = true;
		//e.returnValue = false;
	
		//e.stopPropagation works only in Firefox.
		if (e.stopPropagation) {
			e.stopPropagation();
			//e.preventDefault();
		}
		return false;
	},

    /**
     * Deletes the selected file path from the server
     */
    deleteFile: function(filePath, node) {
        if( !confirm("Delete Selected File: '" + filePath + "' From Server?") ) {
            return;
        }
		
        var query = "action=delete_file&FilePath=" + filePath;
        pageManager.post( file_utils.processorPage, query, function(data) {
			$p('#fu-ajax-result').html(data);
            if( node != null ) file_utils.removeFileNode( node );
        } );
    },

    /**
     * Removes the selected node from the file tree display
     */
    removeFileNode: function(node) {
		
        var parent = file_utils.findFirstParentWithClass( node, 'file_name' );
		
        if( parent != null ) {
            parent.parentNode.removeChild(parent);
        }
    },

    /**
     * Finds the first parent node in the hierachy of the supplied element which has the
     * specified class name.
     */
    findFirstParentWithClass: function(el, cn) {
        if( el.parentNode != null && el.parentNode.className == cn ) {
            return el.parentNode;
        } else if( el.parentNode == null ) {
            return null;
        }
		
        return file_utils.findFirstParentWithClass( el.parentNode, cn );
    },

    /**
     * Generates and sets the file name to be used when a file is uploaded to the server
     *
     * @param field_id the ID of the form element which would contain the Destination file name
     * @param destFolder a String representing the destination folder
     * @param src_file_path a String representing the source/local path of the file to upload
     * @param fn_prefix a String representing a prefix to use for the filename. If this is blank, the prefix "file" would be used
     */
    generateDestinationFileName: function(selector, destFolder, src_file_path, fn_prefix) {
        var field = pageManager.$( selector );
        
        if(field != null) {
            var now = new Date();
            var dateStr = now.getFullYear() + "" + (now.getMonth() + 1) + "" + now.getDate() + "_" + now.getHours() + "" + now.getMinutes() + "" + now.getSeconds();
            var fileName = src_file_path;
            var ext = fileName.substring( fileName.lastIndexOf("."), fileName.length );
            fileName = destFolder + (fn_prefix != null ? fn_prefix : "file") + dateStr + ext.toLowerCase();

            field.value = fileName;
        }
    }
};

pageManager.addLoadEvent( file_utils.init );